package com.hb.trans.mvp.presenter

import android.location.Location
import com.basiclib.base.BasePresenter
import com.basiclib.lifecycle.RxLifecycleUtils
import com.basiclib.network.RetryWithDelay
import com.basiclib.network.RxErrorHandler
import com.hb.trans.bean.Base
import com.hb.trans.bean.Geocoder
import com.hb.trans.bean.Update
import com.hb.trans.global.ErrorHandleSubscriber
import com.hb.trans.mvp.contract.MainContract
import com.hb.trans.mvp.model.MainModel
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject

class MainPresenter @Inject constructor(_mModel: MainModel, var errorHandler: RxErrorHandler) :
    BasePresenter<MainContract.View, MainContract.Model>(_mModel) {
    fun getById() {
        mModel.getById()
            .subscribeOn(Schedulers.io())
            .retryWhen(RetryWithDelay())
            .observeOn(AndroidSchedulers.mainThread())
            .compose(RxLifecycleUtils.bindToLifecycle(mRootView!!))
            .subscribe(object : ErrorHandleSubscriber<Base<Update>>(errorHandler) {
                override fun next(r: Base<Update>) {
                    if (r.code == 1) {
                        mRootView?.setGetById(r.data)
                    } else {
                        mRootView?.showShortToast(r.info ?: "")
                    }
                }
            })
    }

    fun getLocationInfo(location: Location) {
        mModel.getLocationInfo(location)
            .subscribeOn(Schedulers.io())
            .retryWhen(RetryWithDelay())
            .observeOn(AndroidSchedulers.mainThread())
            .compose(RxLifecycleUtils.bindToLifecycle(mRootView!!))
            .subscribe(object : ErrorHandleSubscriber<Geocoder>(errorHandler) {
                override fun next(r: Geocoder) {
                    if (r.status == 0) {
                        val addressComponent = r.result.addressComponent
                        mRootView?.setCurrentLocationCity(
                            addressComponent.province,
                            addressComponent.city,
                            addressComponent.district
                        )
                    } else {
                        mRootView?.showShortToast("获取城市信息失败，请返回重试")
                    }
                }
            })
    }
}